package res

import (
	"github.com/gin-gonic/gin"
	"gvb_server/utils"
)

const (
	SUCCESS = 200
	FAIL    = 500
)

type Response struct {
	Code ErrorCode `json:"code"`
	Msg  any       `json:"msg"`
	Data any       `json:"data"`
}

type PageResponse[T any] struct {
	Count int64 `json:"count"`
	List  T     `json:"list"`
}

func Result(code ErrorCode, msg string, data any, c *gin.Context) {
	c.JSON(200, Response{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

func OK(data any, msg string, c *gin.Context) {
	Result(SUCCESS, msg, data, c)
}

func OKWithPage(list any, count int64, c *gin.Context) {
	OkWithData(PageResponse[any]{
		Count: count,
		List:  list,
	}, c)
}

func OkWith(c *gin.Context) {
	Result(SUCCESS, "ok", nil, c)
}

func OkWithMessage(msg string, c *gin.Context) {
	Result(SUCCESS, msg, nil, c)
}

func OkWithData(data any, c *gin.Context) {
	Result(SUCCESS, "ok", data, c)
}

func OkWithMsg(msg string, c *gin.Context) {
	Result(SUCCESS, msg, nil, c)
}

func Fail(msg string, c *gin.Context) {
	Result(FAIL, msg, nil, c)
}

func FailWithError(err error, obj any, c *gin.Context) {
	msg := utils.GetValidMsg(err, obj)
	Fail(msg, c)
}

func FailCode(errCode ErrorCode, c *gin.Context) {
	if msg, ok := ErrCodeMap[errCode]; ok {
		Result(errCode, msg, nil, c)
	} else {
		Result(errCode, "未知错误", nil, c)
	}
}
